
const Controller = require('egg').Controller

/**
 * @controller 鉴权 Auth
 */
class AuthController extends Controller {
  /**
   * @summary 登录
   * @router post /login
   * @request query string code code
   * @response 200 response<loginRes> OK
   */
  async login() {
    const { ctx } = this
    // 校验
    // const validateResult = await this.ctx.validate('auth.login', ctx.query)
    // if (!validateResult) return
    // 调用service层方法
    const res = await ctx.service.auth.login(ctx.request.body)
    if (res) {
      ctx.renderBack(res)
    }
  }

  async register() {
    const { ctx } = this
    const res = await ctx.service.auth.register(ctx.request.body)
    if (res === -1) {
      return ctx.renderBack(null, '0', '用户已经存在')
    }
    if (res === -2) {
      return ctx.renderBack(null, '0', '邮箱已经注册')
    }
    if (res) {
      ctx.renderBack(null, '1', '注册成功')
    }
  }
  /**
   * @summary token刷新
   * @router post /refreshToken
   * @request body refreshReq
   * @response 200 response<refreshRes> OK
   */
  async refreshToken() {
    const { ctx } = this
    const validateResult = await ctx.validate('auth.refreshToken', ctx.request.body)
    if (!validateResult) return

    const res = await ctx.service.auth.refreshToken(ctx.request.body.token)
    if (res) {
      ctx.renderBack(res)
    }
  }
}

module.exports = AuthController
